package com.zzr.zzrbackend.service.Impl;

import com.zzr.zzrbackend.mapper.AiAudioMapper;
import com.zzr.zzrbackend.mapper.AiInitAudioMapper;
import com.zzr.zzrbackend.mapper.AiServerMapper;
import com.zzr.zzrbackend.mapper.MouseServerMapper;
import com.zzr.zzrbackend.pojo.domain.AiAudio;
import com.zzr.zzrbackend.pojo.domain.AiInitAudio;
import com.zzr.zzrbackend.pojo.dto.CommonResult;
import com.zzr.zzrbackend.pojo.dto.param.AudioInitParam;
import com.zzr.zzrbackend.pojo.dto.result.NoData;
import com.zzr.zzrbackend.service.AudioService;
import com.zzr.zzrbackend.util.TokenUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AudioServiceImpl implements AudioService {

    @Resource
    private AiInitAudioMapper aiInitAudioMapper;
    @Resource
    private AiServerMapper aiServerMapper;
    @Resource
    private AiAudioMapper aiAudioMapper;
    @Resource
    private MouseServerMapper mouseServerMapper;

    @Override
    public CommonResult<NoData> setAudioInit(HttpServletRequest request, AudioInitParam audioInitParam) {
        Claims claims = TokenUtils.getClaimsFromJwt(request.getHeader("token"));
        Integer permission = (Integer) claims.get("permission");
        if (permission == 2) {
            Integer userId = (Integer) claims.get("id");
            AiInitAudio aiInitAudioExist = aiInitAudioMapper.selectByUserId(userId);
            AiInitAudio aiInitAudio = new AiInitAudio();
            aiInitAudio.setUser_id(userId);
            aiInitAudio.setAudioInitUrl(audioInitParam.getAudioUrl());
            if (aiInitAudioExist == null) {
                aiInitAudioMapper.insert(aiInitAudio);
            } else {
                aiInitAudioMapper.update(aiInitAudio);
            }
            return CommonResult.success();
        } else {
            return CommonResult.fail("权限异常");
        }
    }

    @Override
    public CommonResult<NoData> getServer(HttpServletRequest request) {
        return CommonResult.success(aiServerMapper.selectServer());
    }

    @Override
    public CommonResult<NoData> getAiCache(HttpServletRequest request, Integer contentInfoId) {
        Claims claims = TokenUtils.getClaimsFromJwt(request.getHeader("token"));
        Integer userId = (Integer) claims.get("id");
        List<AiAudio> aiAudio = aiAudioMapper.selectByContentInfoIdAndUserId(contentInfoId, userId);
        if (aiAudio.size() == 0) {
            return CommonResult.fail("无缓存");
        } else {
            return CommonResult.success(aiAudio.get(0).getAudioUrl());
        }
    }

    @Override
    public CommonResult<NoData> getMouseServer(HttpServletRequest request) {
        return CommonResult.success(mouseServerMapper.selectServer());
    }
}
